﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AbpCodeBuilder.CodeHelper;

namespace AbpCodeBulider.DxUI
{
    internal partial class FrmSlnRename4Abp : FrmBase
    {
        public FrmSlnRename4Abp()
        {
            InitializeComponent();
        }

        private void FrmSlnRename4Abp_Load(object sender, EventArgs e)
        {
            this.rec.ScrollToCaret();
        }

        private void btnOpenSlnDir_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string currentDirPath = fbd.SelectedPath;

                this.txtSlnDir.Text = currentDirPath;

                HandlerReadDir(currentDirPath);

            }
        }

        private void txtSlnDir_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char) Keys.Enter)
            {
                string currentDirPath = this.txtSlnDir.Text;

                if (string.IsNullOrWhiteSpace(currentDirPath))
                {
                    return;
                }

                HandlerReadDir(currentDirPath);
            }
        }

        private void HandlerReadDir(string currentDirPath)
        {
            
            string slnFullName = Directory.GetFiles(currentDirPath, "*.sln").FirstOrDefault();
            string oldSlnName = string.Empty;
            if (!string.IsNullOrWhiteSpace(slnFullName))
            {
                oldSlnName = slnFullName.Remove(0, slnFullName.LastIndexOf("\\", StringComparison.Ordinal) + 1);
                txtOldSlnName.Text = oldSlnName;
            }

            string oldCompanyName = string.Empty;
            if (!string.IsNullOrWhiteSpace(oldSlnName))
            {
                oldCompanyName = oldSlnName.Substring(0, oldSlnName.IndexOf(".", StringComparison.Ordinal));
                txtOldCompanyName.Text = oldCompanyName;
            }

            string oldProjectName = string.Empty;
            if (!string.IsNullOrWhiteSpace(oldSlnName) && oldSlnName.Count(c => c.Equals('.')) > 1)
            {
                oldProjectName = oldSlnName.Remove(0, oldSlnName.IndexOf(".", StringComparison.Ordinal) + 1);
                oldProjectName = oldProjectName.Substring(0, oldProjectName.IndexOf(".", StringComparison.Ordinal));

                txtOldProjectName.Text = oldProjectName;
            }
            
            //try
            //{
            //    SolutionRenamer solutionRenamer = new SolutionRenamer(currentDirPath, oldCompanyName, oldProjectName,
            //            newCompanyName, newProjectName, append)
            //    { CreateBackup = false };
            //    solutionRenamer.Run();
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("请删除目录下的.vs目录、node_modules目录");
            //}

        }

        private void btnRename_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtOldCompanyName.Text.Trim()))
            {
                MessageBox.Show("请读取旧的解决方案公司名");
                txtOldCompanyName.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtOldProjectName.Text.Trim()))
            {
                MessageBox.Show("请读取旧的解决方案项目名");
                txtOldProjectName.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtNewCompanyName.Text.Trim()))
            {
                MessageBox.Show("请输入新的解决方案公司名");
                txtNewCompanyName.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtNewProjectName.Text.Trim()))
            {
                MessageBox.Show("请输入新的解决方案项目名");
                txtNewProjectName.Focus();
                return;
            }

            string currentDirPath = this.txtSlnDir.Text;

            if (string.IsNullOrWhiteSpace(currentDirPath))
            {
                return;
            }

            
            Queue consoleQueue = Queue.Synchronized(new Queue());
            var append = new Action<string>(content => {
                consoleQueue.Enqueue(content);
                //if (this.InvokeRequired)
                //{
                //    this.Invoke(new MethodInvoker(() => { this.rec.Text = this.rec.Text + content + "\r\n"; }));
                //}
                //else
                //{
                //    this.rec.Text = this.rec.Text + content + "\r\n";
                //}
            });

            var oldCompanyName = txtOldCompanyName.Text;
            var oldProjectName = txtOldProjectName.Text;

            var newCompanyName = txtNewCompanyName.Text.Trim();
            var newProjectName = txtNewProjectName.Text.Trim();

            try
            {
                WaitForm.ShowWaitForm();
                bool isOk = false;
                new Thread(() =>
                {
                    SolutionRenamer solutionRenamer = new SolutionRenamer(currentDirPath, oldCompanyName,
                            oldProjectName,
                            newCompanyName, newProjectName, append)
                        {CreateBackup = false};

                    solutionRenamer.Run();
                    isOk = true;
                    WaitForm.CloseWaitForm();
                }) {IsBackground = true}.Start();


                new Thread(() =>
                    {
                        StringBuilder str = new StringBuilder();
                        while (true)
                        {

                            var count = !isOk ? 20 : consoleQueue.Count;
                            for (int i = 0; i < count; i++)
                            {
                                if (consoleQueue.Count > 0)
                                {
                                    var text = consoleQueue.Dequeue().ToString();
                                    if (!string.IsNullOrWhiteSpace(text))
                                    {
                                        str.AppendLine(text);
                                    }

                                    if (i + 1 == count)
                                    {
                                        if (this.InvokeRequired)
                                        {
                                            this.Invoke(new MethodInvoker(() =>
                                            {
                                                this.rec.Text = str.ToString();
                                                rec.Document.CaretPosition = rec.Document.Range.End;
                                                rec.ScrollToCaret();
                                            }));

                                        }
                                        else
                                        {
                                            this.rec.Text = str.ToString();
                                            rec.Document.CaretPosition = rec.Document.Range.End;
                                            rec.ScrollToCaret();
                                        }
                                    }
                                }
                            }

                            if (consoleQueue.Count == 0 && isOk) break;
                            Thread.Sleep(300);
                        }

                        if (this.InvokeRequired)
                        {
                            this.Invoke(new MethodInvoker(() =>
                            {
                                this.rec.Text += "重写成功";
                                rec.Document.CaretPosition = rec.Document.Range.End;
                                rec.ScrollToCaret();
                            }));
                        }
                        else
                        {
                            this.rec.Text = this.rec.Text += "重写成功";
                            rec.Document.CaretPosition = rec.Document.Range.End;
                            rec.ScrollToCaret();
                        }
                    })
                    {IsBackground = true}.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show("请删除目录下的.vs目录、node_modules目录");
            }
        }

        private void btnRead_Click(object sender, EventArgs e)
        {
            string currentDirPath = this.txtSlnDir.Text;

            if (string.IsNullOrWhiteSpace(currentDirPath))
            {
                return;
            }

            HandlerReadDir(currentDirPath);
        }

        private void txtNewCompanyName_EditValueChanged(object sender, EventArgs e)
        {
            this.txtNewSlnName.Text = $"{this.txtNewCompanyName.Text}.{this.txtNewProjectName.Text}";
        }

        private void txtNewProjectName_EditValueChanged(object sender, EventArgs e)
        {
            this.txtNewSlnName.Text = $"{this.txtNewCompanyName.Text}.{this.txtNewProjectName.Text}";
        }
    }
}
